<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input
      type="text"
      v-model="addName"

      />
    </div>
    <div>
      <button @click="add" :disabled="disable"  >添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>图书名称</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        <tbody>

          <books
          :arr="item"
          v-for="item in list"
          :key="item.id"
          :getall="getAll"
          @edit="Edit"
          :list="list"/>
        </tbody>

      </table>
    </div>
  </div>
</template>
<script>
import Books from './components/Books'
import axios from 'axios'
axios.defaults.baseURL = 'http://liufusong.top:4000/'
export default {
  components: { Books },
  data () {
    return {
      list: [],
      addName: '',
      disable: false
    }
  },
  created () {
    this.getAll()
  },
  methods: {
    async getAll () {
      try {
        const res = await axios({
          url: 'books'

        })
        this.list = res.data
      } catch (error) {
        alert('出错了')
      }
    },
    async add () {
      // else if (this.list.some(item => item.name === this.addName)) {
      //   this.disable = true
      //   alert('重复输入')
      //   this.addName = ''
      //   this.disable = false
      // }

      if (this.addName.trim() === '') {
        return alert('请输入内容')
      } else {
        try {
          const res = await axios({
            url: 'books/book/' + this.addName
          })
          console.log(res.data)
          if (res.data.status === 1) {
            this.disable = true
            this.addName = ''
            this.disable = false
          } else {
            try {
              await axios({
                url: 'books',
                method: 'POST',
                data: {
                  name: this.addName
                }
              })

              this.getAll()
              this.addName = ''
              // console.log(this.name)
              // console.log(this.list.data)

            // 将得到的name传进去里面
            } catch (error) {
              alert('出错了')
            }
          }
        } catch (error) {
          alert('出错了')
        }
      }
    },
    Edit (e) {
      this.addName = e
      console.log(e)
    }
  }
}
</script>
